'use strict';
const http = require('http'); //nodejs提供操作http模块的核心对象
let msgList = [{ nickname: 'jack', msg: '你好' }, { nickname: 'rose', msg: '很好' }];

let server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/msg/getMsg') { //ajax获取最新的消息数据
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.end(JSON.stringify({ message: msgList }));
    } else if (req.method === 'POST' && req.url === '/msg/sendMsg') {

        let totalData = '';
        req.on('data', (data) => {
            totalData += data;
        });
        req.on('end', () => { //获取数据
            let obj = require('querystring').parse(totalData);
            //将数据插入到数组中
            msgList.push(obj);
            res.setHeader('Access-Control-Allow-Origin', '*')
                //将新数据返回给响应
            res.end(JSON.stringify({ message: { code: '001', msgs: msgList } }));
        });

    } else if (req.method === 'POST' && req.url === '/login') {
        let totalData = '';
        req.on('data', (data) => {
            totalData += data;
        });
        req.on('end', () => { //获取数据
            let obj = require('querystring').parse(totalData);
            res.setHeader('Access-Control-Allow-Origin', '*')
                //将新数据返回给响应
            if (obj.password == '123' && obj.username == '123')
                return res.end(JSON.stringify({ code: '001', msg: '成功' }));
            else
                return res.end(JSON.stringify({ code: '002', msg: '失败' }));
        });
    }
});
server.listen(80, () => {
    console.log('聊天室监听了80端口')
});







require('./base.js')(server);
